package com.chyb.cloud.controller;

import com.chyb.cloud.entities.PayDTO;
import com.chyb.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
public class OrderController {
//    public static final String PaymentSrv_URL = "http://localhost:8001/pay";

    public static final String PaymentSrv_URL = "http://cloud-payment-service/pay";

    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/add")
    public ResultData create(@RequestBody PayDTO payDTO) {
        return restTemplate.postForObject(PaymentSrv_URL + "/add", payDTO, ResultData.class);
    }

    @GetMapping("/getInfo/{id}")
    public ResultData getInfo(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PaymentSrv_URL + "/get/" + id, ResultData.class, id);
    }

    @GetMapping("/getAll")
    public ResultData getAll() {
        return restTemplate.getForObject(PaymentSrv_URL + "/getAll", ResultData.class);
    }

    @DeleteMapping("/delete/{id}")
    public ResultData delete(@PathVariable("id") Integer id) {
        // 使用 delete() 方法发送 DELETE 请求
        restTemplate.delete(PaymentSrv_URL + "/delete/" + id);
        return ResultData.success("删除成功");
    }

    @PutMapping("/update/")
    public ResultData update(@RequestBody PayDTO payDTO) {
        return restTemplate.postForObject(PaymentSrv_URL + "/update", payDTO, ResultData.class);
    }

    @GetMapping("/get/Info")
    public String getInfo() {
        return restTemplate.getForObject(PaymentSrv_URL + "/getInfo", String.class);
    }



    /*注入客户端实例*/
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/discovery")
    public String discovery()
    {
        /*获取所有的服务*/
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }

        System.out.println("===================================");

        /*将获取到的实例，提取服务名为：cloud-payment-service的实例*/
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance element : instances) {
            System.out.println(element.getServiceId()+"\t"+element.getHost()+"\t"+element.getPort()+"\t"+element.getUri());
        }
        return instances.get(0).getServiceId()+":"+instances.get(0).getPort();
    }
}
